﻿#define _CRT_SECURE_NO_WARNINGS 1
#include"SeqList.h"

//初始化顺序表的定义
void SLInit(SL* ps)
{
	ps->arr = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

//顺序表的尾插的定义
void SLPushBack(SL* ps, SLType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	ps->arr[ps->size] = x;
	ps->size++;
}

//空间扩容的定义
void SLCheckCapacity(SL* ps)
{
	if (ps->size == ps->capacity)
	{
		//增容
		int Newcapacity = (ps->capacity == 0 ? 4 : 2 * ps->capacity);
		SLType* tmp = (SLType*)realloc(ps->arr, Newcapacity * sizeof(SLType));
		if (tmp == NULL)
		{
			perror("realloc faile");//判断原因
			exit(1);//退出程序
		}
		//空间申请成功
		ps->arr = tmp;
		ps->capacity = Newcapacity;
	}
}
//顺序表的打印的定义
void SLPrint(SL* ps)
{
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("\n");
}

//顺序表的头插的定义
void SLPushFront(SL* ps, SLType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	int i = 0;
	for (i = ps->size; i > 0; i--)
	{
		ps->arr[i] = ps->arr[i - 1];//arr[1] = arr[0]
	}
	ps->arr[i] = x;
	ps->size++;
}

//顺序表的尾删的定义
void SLPopBack(SL* ps)
{
	assert(ps);
	assert(ps->size);
	ps->size--;
}

//顺序表的头删的定义
void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size);
	int i = 0;
	for (i = 0; i < ps->size - 1; i++)//size = 4
	{
		ps->arr[i] = ps->arr[i + 1];//arr[2] = arr[3]
	}
	ps->size--;
}

//指定位置之前插⼊数据
void SLInsert(SL* ps, int pos, SLType x)//pos--要插入的位置的下标
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	int i = 0;
	for (i = ps->size; i > pos; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[i] = x;
	ps->size++;
}

//指定位置之前删除数据
void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(ps->size);
	assert(pos >= 0 && pos < ps->size);
	for (int i = pos; i < ps->size - 1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

//查找
int SLFind(SL* ps, SLType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == x)
			return i;
	}
	return -1;
}

//顺序表的销毁的定义
void SLDestroy(SL* ps)
{
	if (ps->arr)
	{
		free(ps->arr);
		ps->arr = NULL;
		ps->size = ps->capacity = 0;
	 }
}